package com.epfresh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.epfresh.R;
import com.epfresh.adapter.ColumnDetailProductViewBinder;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.bean.ColumnDetailBean;
import com.epfresh.bean.HomeColumnBean;
import com.epfresh.global.BaseActivity;
import com.epfresh.views.MultiStateView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import multitype.MultiTypeAdapter;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;

public class ColumnDetailActivity extends BaseActivity {
    private MultiStateView msv;
    private PtrFrameLayout ptr;
    private RecyclerView rv;
    private String columnId;
    private MultiTypeAdapter multiAdapter;
    private List<Object> items = new ArrayList<>();
    private LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();
    private boolean isInit = true;
    private boolean isRefresh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_column_detail);

        String title = getIntent().getStringExtra("title");
        basetitle.setText(title);

        initView();
        columnId = getIntent().getStringExtra("columnId");
        refresh();

    }

    private void initView() {
        msv = findViewById(R.id.msv);
        ptr = findViewById(R.id.ptr);
        rv = findViewById(R.id.rv);
        multiAdapter = new MultiTypeAdapter();

        msv.setViewForState(R.layout.loading_view, MultiStateView.VIEW_STATE_LOADING);
        msv.setViewForState(R.layout.empty_view, MultiStateView.VIEW_STATE_EMPTY);
        ptr.setPtrHandler(ptrHandler);
        loadMoreDelegate.attach(rv, loadMoreSubject);

        ColumnDetailProductViewBinder columnDetailProductViewBinder = new ColumnDetailProductViewBinder();
        columnDetailProductViewBinder.setOnItemClickListener(new ColumnDetailProductViewBinder.OnItemClickListener() {
            @Override
            public void onItemClick(HomeColumnBean.ProductsBean item) {
                Intent intent = new Intent(ColumnDetailActivity.this, DetailGoodsActivity.class);
                intent.putExtra("storeId", String.valueOf(item.getStoreId()));
                intent.putExtra("id", String.valueOf(item.getProductSpecPrice().getProductSpecId()));
                startActivity(intent);
            }
        });
        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        multiAdapter.register(HomeColumnBean.ProductsBean.class, columnDetailProductViewBinder);
        multiAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        multiAdapter.setItems(items);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                Object o = items.get(position);
                return o instanceof HomeColumnBean.ProductsBean ? 1 : 2;
            }
        };
        gridLayoutManager.setSpanSizeLookup(spanSizeLookup);
        rv.setLayoutManager(gridLayoutManager);
        rv.setAdapter(multiAdapter);

    }
    

    /**
     * 刷新
     */
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void refresh() {
        if (TextUtils.isEmpty(columnId))
            return;
        isRefresh = true;
        reqData(columnId);
    }

    /**
     * 加载更多
     */
    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptr.isRefreshing();
        }

        @Override
        public void onLoadMore() {
            loadMore();
        }
    };

    private void loadMore() {
        if (TextUtils.isEmpty(columnId))
            return;
        isRefresh = false;
        reqData(columnId);
    }


    private void reqData(String columnId) {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(AppPurchaseRouterConstant.cmd_column_detail);
        re.putParameter("columnId", columnId);

        request(re, AppPurchaseRouterConstant.cmd_column_detail, new OnRequestListener<ColumnDetailBean>() {

            @Override
            public ColumnDetailBean jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, ColumnDetailBean.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
//                msv.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                ptr.refreshComplete();
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
//                msv.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                ptr.refreshComplete();
            }

            @Override
            public void onStart(Object tag) {
                if (isInit) {
                    msv.setViewState(MultiStateView.VIEW_STATE_LOADING);
                    isInit = false;
                }
            }

            @Override
            public void onResponse(ResponseEntity<ColumnDetailBean> response, Object tag) {
                ptr.refreshComplete();
                if (response.getResponseElement().getProducts() != null && response.getResponseElement().getProducts().size() > 0) {
                    msv.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                    if (isRefresh) {
                        items.clear();
                    }
                    loadMoreDelegate.addAllItem(items, response.getResponseElement().getProducts());
                    boolean isLast = true;
                    if (isLast) {
                        loadMoreDelegate.setStatusNoMore();
                    } else {
                        loadMoreDelegate.setStatusNormal();
                    }
                    multiAdapter.notifyDataSetChanged();

                } else {
                    msv.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                }
            }
        });
    }
}
